// pages/divination/divination-process/divination-process.js

let app = getApp()
const DIVINA_CONTENT = ['老阳', '少阴', '少阳', '老阴']
const ORDER = ['上爻', '五爻', '四爻', '三爻', '二爻', '初爻']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    barTitle: '',
    turtleShake: '',
    isShake: false,
    coinRandom: ["", "", ""],
    coinMoveClass: [],
    count: 0,
    divinationResult: [],
    isShowUnlock: false,
    triangleCount: 0,
    animationData: {},
    isSoundPlay: true,
    event: {},
    resultCode: [],
    isGuideShow: true,
    resultId: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let tempArray = this.data.divinationResult
    for (let i = 0; i < ORDER.length; i++) {
      let o = {}
      o.order = ORDER[i]
      tempArray.push(o)
    }
    this.setData({
      barTitle: options.name,
      event: {
        eventId: options.id, // 种类ID
        price: options.price,
        unlock: options.unlock
      },
      divinationResult: tempArray
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 设置导航条标题
    // wx.startAccelerometer()
    wx.setNavigationBarTitle({
      title: "您当前占卜的是：" + this.data.barTitle
    })

    // 摇一摇监听加速度计
    wx.onAccelerometerChange((res) => {
      // if (this.data.count >= 6) {
      //   wx.stopAccelerometer()
      // }
      console.log("y", res.y)
      if (res.x > 0.6 || res.y > 0.6) {
        this.startShake()
      }
    })

    // 播放音频
    this.audioCtx = wx.createAudioContext('sound')
    this.audioCtx.play()



    // 创建引导动画
    let animation = wx.createAnimation({
      duration: 1200,
      timingFunction: 'ease',
    })
    this.animation = animation
  },
  fade() {
    this.animation.opacity(0).step()
    this.setData({
      animationData: this.animation.export()
    })
    setTimeout(() => {
      this.setData({
        isGuideShow: false
      })
    }, 1500)
  },
  startShake() {
    if (this.data.isGuideShow) return
    if (this.data.isShake) return false
    if (this.data.count >= 6) {
      this.showUnlock()
      return false
    }
    this.setData({
      turtleShake: 'turtle-shake',
      isShake: !this.data.isShake,
      count: this.data.count + 1
    })

    this.audioCtx = wx.createAudioContext('soundShake')
    this.audioCtx.play()
    this.audioCtx = wx.createAudioContext('sound')

    this.getCoinArray()
    this.coinMove().then(() => {
      this.getDivinationItem()
      if (this.data.count >= 6) {
        setTimeout(() => {
          this.showUnlock()
        }, 1500)
      }
    })

    setTimeout(() => {
      this.setData({
        turtleShake: '',
        isShake: !this.data.isShake,
      })
    }, 1500)


  },

  coinMove() {
    return new Promise((resolve, reject) => {
      this.setData({
        coinMoveClass: ['coin1-move', 'coin2-move', 'coin3-move']
      })
      setTimeout(() => {
        this.setData({
          coinMoveClass: []
        })
        resolve();
      }, 1500)
    })

  },
  getCoinArray() {
    let coinRandom = [];
    for (let i = 0; i < 3; i++) {
      coinRandom.push(Math.abs(Math.ceil(0.5 - Math.random())))
    }
    this.setData({
      coinRandom: coinRandom
    })

  },
  /**
   * 得到每一卦的内容
   */
  getDivinationItem() {
    let count = this.data.count
    let resultCode = this.data.resultCode
    let aResult = this.data.coinRandom.filter((item, index) => {
      return item === 1
    })
    let len = aResult.length
    resultCode.push(4 - len)
    let temp = {
      show: len,
      text: DIVINA_CONTENT[len]
    }

    let divinationResult = this.data.divinationResult
    divinationResult[6 - count].content = temp
    this.setData({
      divinationResult: divinationResult,
      resultCode: resultCode
    })
    setTimeout(() => {
      this.setData({
        triangleCount: count
      })
    }, 1000)

  },
  /**
   * 判断是否显示立即解卦弹窗
   */
  showUnlock() {
    this.setData({
      isShowUnlock: true
    })
  },
  /**
   * 点击立即解卦
   */
  unlock() {
    let isPay = true
    let item = this.data.event

    this.getResult().then((data) => {
      console.log(data.reports_id)
      return data.reports_id
    }).then((id) => {
      if ((item.price > 0 && item.unlock == 1) || item.price == 0) {
        wx.redirectTo({
          url: `../divination-detail/divination-detail?resultId=${id}`,
        })

      } else {
        app.request("get_payment_params", { cat_id: item.eventId, rep_id: id }, true).then((data) => {
          console.log(data)
          if (data.code != 0) {
            wx.showModal({
              title: '请求错误',
              content: data.message,
              showCancel: false,
              confirmColor: '#000'
            })
          } else {
            data.wxpay.success = (res) => {
              console.log("支付成功", res)
              wx.showLoading({
                title: '请稍候'
              })
              let tem = setInterval(() => {
                app.request("get_locks", { cat_id: item.eventId }, true).then((data) => {
                  console.log(data)
                  if (data.code == 0) {
                    // this.getResult().then((data) => {
                      clearInterval(tem)
                      wx.hideLoading()
                      wx.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1500
                      })
                      setTimeout(() => {
                        wx.redirectTo({
                          url: `../divination-detail/divination-detail?resultId=${id}`,
                        })
                      }, 1500)
                    // })

                  }
                })
              }, 500)

            }
            data.wxpay.fail = function (res) {
              console.log("支付失败", res)
              console.log(res)
              wx.showModal({
                title: '支付已取消',
                showCancel: false,
                confirmColor: '#000'
              })
            }
            wx.requestPayment(data.wxpay)
          }
        })

      }
    })


  },
  close() {
    this.setData({
      isShowUnlock: false
    })
  },
  playVoice() {
    if (this.data.isSoundPlay) {
      this.setData({
        isSoundPlay: !this.data.isSoundPlay
      })
      this.audioCtx.pause()
    } else {
      this.setData({
        isSoundPlay: !this.data.isSoundPlay
      })
      this.audioCtx.play()
    }

  },
  getResult() {
    return new Promise((resolve, reject) => {
      let that = this
      app.request("submit_report", {
        code: that.data.resultCode.join(""),
        cat_id: that.data.event.eventId
      }, true).then((data) => {
        resolve(data)
      })
    })
  },
  onShareAppMessage: function (res) {
    return {
      title: '每日一卦',
      path: '/pages/divination/divination',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})